package tech.aistar.day07.homework;

/**
 * 本类用来演示: 找出俩个字符串中的最长长度的公串
 *
 * @author: success
 * @date: 2022/7/27 8:45 上午
 */
public class FindCommonStrDemo {
    public static void main(String[] args) {
        String firstStr = "djdjfabcooooofpsdfd";
        String secStr = "djdjffdjkfjkdoooooeww";
        System.out.println(find(firstStr,secStr));
    }
    //可能是多个

    /**
     * 遍历长度短一点的字符 - 外层循环
     * @param firstStr 假设短一点
     * @param SecStr
     * @return
     */
    public static StringBuilder find(String firstStr,String SecStr){
        StringBuilder builder = new StringBuilder();
        int initLen = 0;
        //找出短一点字符串中所有的子串
        for (int i = 0; i < firstStr.length(); i++) {
            for (int j = i+1; j < firstStr.length(); j++) {
                //判断子串在SecStr中是否存在
                String subStr = firstStr.substring(i,j);
                //取出该子串的长度
                int len = subStr.length();

                if(SecStr.contains(subStr) && len>initLen){
                    //清空一下builder
                    builder.delete(0,builder.length());
                    builder.append(subStr+" ");
                    initLen = len;
                }else if(SecStr.contains(subStr) && len==initLen){
                    builder.append(subStr+" ");
                }
            }
        }
        return builder;
    }
}
